<?php
/*
 +----------------------------------------------------------------------
 + Title        : HttpResponseException 控制器
 + Author       : Randy_chen
 + Version      : V1.0.0.1
 + Initial-Time : 2019/8/7 14:39
 + Last-time    : 2019/8/7 14:39+ 86187
 + Desc         : HttpResponseException
 +----------------------------------------------------------------------
*/


namespace app\http\exception;


use function Sodium\add;
use think\facade\Request;
use think\Response;

class HttpResponseException extends \think\exception\HttpResponseException
{
    /**
     * @var Response
     */
    protected $response;

    public function __construct(Response $response)
    {
        $this->response = $response;
    }

    public function getResponse()
    {
        return $this->response;
    }

    //记录接口日志
    public function log(){
        $service = new \app\api\service\ApiChannel();
        $channel = $service->getToken(Request::param('access_token'));//['channel_id'];
        $channel_id = $channel ? $channel['channel_id'] : '';
        $response = $this->response->getData();
        $add['request_time'] = get_microtime_format(Request::time(true));
        $add['create_time'] = date('Y-m-d H:i:s');
        $add['response_time'] = get_microtime_format(microtime(true));
        $add['request'] = json_encode(Request::param(),JSON_UNESCAPED_UNICODE);
        $add['ip'] = Request::ip();
        $add['response'] =  json_encode($response,JSON_UNESCAPED_UNICODE);;
        $add['channel_id'] =$channel_id;
        $add['code'] = $response['code'];
        $add['msg'] = $response['msg'];
        $add['url'] = Request::baseUrl();
        $add['query'] = json_encode(Request::get() , JSON_UNESCAPED_UNICODE);
        $add['header'] = json_encode(Request::header() , JSON_UNESCAPED_UNICODE);
        try {
            db('api_log')
                ->strict(false)
                ->insert($add);
        } catch (\Exception $e) {
        }
    }
}